<template>
  <div class="app-container">
    <div class="header">
      <h1>PDF打印与预览</h1>
      <p class="description">使用pdfmake生成复杂表单，vue-pdf实现预览</p>
    </div>

    <el-card class="pdf-controls">
      <div slot="header" class="clearfix">
        <span>控制面板</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="showFormDialog = true"
        >
          编辑表单
        </el-button>
      </div>

      <el-form :model="formData" label-width="100px" class="form-panel">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="报告编号">
              <el-input
                v-model="formData.reportNo"
                placeholder="请输入报告编号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务类型">
              <el-select
                v-model="formData.businessType"
                placeholder="请选择业务类型"
              >
                <el-option label="销售业务" value="销售业务" />
                <el-option label="客户服务" value="客户服务" />
                <el-option label="技术支持" value="技术支持" />
                <el-option label="市场推广" value="市场推广" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="负责人">
              <el-input v-model="formData.manager" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-button-group class="action-buttons">
          <el-button
            type="primary"
            icon="el-icon-view"
            @click="handlePreview"
            :loading="previewLoading"
          >
            预览PDF
          </el-button>
          <el-button
            type="success"
            icon="el-icon-printer"
            @click="handlePrint"
            :loading="printLoading"
          >
            打印PDF
          </el-button>
          <el-button
            type="warning"
            icon="el-icon-download"
            @click="handleDownload"
            :loading="downloadLoading"
          >
            下载PDF
          </el-button>
          <el-button type="info" icon="el-icon-back" @click="goBack">
            返回
          </el-button>
        </el-button-group>
      </el-form>
    </el-card>

    <!-- PDF预览对话框 -->
    <el-dialog
      :visible.sync="previewVisible"
      title="PDF预览"
      width="90%"
      top="5vh"
      :fullscreen="isFullscreen"
    >
      <div class="pdf-preview-container">
        <div class="preview-toolbar">
          <el-button-group>
            <el-button
              size="small"
              @click="currentPage = Math.max(1, currentPage - 1)"
              :disabled="currentPage <= 1"
            >
              上一页
            </el-button>
            <el-button
              size="small"
              @click="currentPage = Math.min(totalPages, currentPage + 1)"
              :disabled="currentPage >= totalPages"
            >
              下一页
            </el-button>
          </el-button-group>

          <span class="page-info">
            第 {{ currentPage }} 页 / 共 {{ totalPages }} 页
          </span>

          <el-button-group style="float: right">
            <el-button
              size="small"
              icon="el-icon-full-screen"
              @click="isFullscreen = !isFullscreen"
            >
              {{ isFullscreen ? "退出全屏" : "全屏" }}
            </el-button>
            <el-button
              size="small"
              icon="el-icon-close"
              @click="previewVisible = false"
            >
              关闭
            </el-button>
          </el-button-group>
        </div>

        <div class="pdf-viewer">
          <pdf
            :src="previewUrl"
            :page="currentPage"
            @num-pages="totalPages = $event"
            @page-loaded="currentPage = $event"
            class="pdf-document"
          />
        </div>
      </div>
    </el-dialog>

    <!-- 表单编辑对话框 -->
    <el-dialog
      :visible.sync="showFormDialog"
      title="编辑表单数据"
      width="600px"
    >
      <el-form :model="formData" label-width="120px">
        <el-form-item label="报告编号">
          <el-input v-model="formData.reportNo" />
        </el-form-item>

        <el-form-item label="业务类型">
          <el-select v-model="formData.businessType" style="width: 100%">
            <el-option label="销售业务" value="销售业务" />
            <el-option label="客户服务" value="客户服务" />
            <el-option label="技术支持" value="技术支持" />
            <el-option label="市场推广" value="市场推广" />
          </el-select>
        </el-form-item>

        <el-form-item label="负责人">
          <el-input v-model="formData.manager" />
        </el-form-item>

        <el-form-item label="部门">
          <el-input v-model="formData.department" />
        </el-form-item>

        <el-form-item label="联系电话">
          <el-input v-model="formData.phone" />
        </el-form-item>

        <el-form-item label="备注信息">
          <el-input
            v-model="formData.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="showFormDialog = false">取消</el-button>
        <el-button type="primary" @click="showFormDialog = false"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import pdf from "vue-pdf";
import PdfService from "@/utils/pdf-service";

/**
 * PDF打印与预览页面
 * 使用pdfmake生成复杂表单，vue-pdf实现预览功能
 */
export default {
  name: "PdfPreview",

  components: {
    pdf,
  },

  data() {
    return {
      previewVisible: false,
      previewUrl: "",
      previewLoading: false,
      printLoading: false,
      downloadLoading: false,
      showFormDialog: false,
      isFullscreen: false,
      currentPage: 1,
      totalPages: 0,

      formData: {
        reportNo: `REP-${new Date().getTime()}`,
        businessType: "销售业务",
        manager: "管理员",
        department: "业务部",
        phone: "13800138000",
        remarks: "",
        tableData: [
          {
            name: "业务收入",
            value: "¥1,234,567",
            trend: "上升",
            rate: "+15%",
          },
          { name: "用户数量", value: "10,000", trend: "稳定", rate: "+2%" },
          { name: "订单数量", value: "5,678", trend: "下降", rate: "-5%" },
          { name: "客户满意度", value: "92%", trend: "上升", rate: "+3%" },
        ],
      },
    };
  },

  methods: {
    /**
     * 处理PDF预览
     * 使用pdfmake生成PDF并使用vue-pdf预览
     */
    handlePreview() {
      const content = {
        content: [
          {
            text: '测试珺啊墚汻罓',
          },
          {
            text: '国网福建福州供电公司',
          },
          {
            text: '配电第二种工作票',
          },
        ],
        defaultStyle: {
          font: "songti",
        },
      };
      PdfService.openPdf(content);
    },
    async handlePreview1() {
      this.previewLoading = true;
      try {
        const content = {
          content: [
            "配电一种票珺",
            "Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines",
          ],
          defaultStyle: {
            font: "songti",
          },
        };
        PdfService.openPdf(content);
        const blobData = await PdfService.exportData(content);
        console.log("[ blobData ] ===", blobData);
        const task = pdf.createLoadingTask(URL.createObjectURL(blobData));
        console.log("[ task ] ===", task);
        // const docDefinition = PdfService.createBusinessReport(this.formData)
        // const { url } = await PdfService.generatePdf(docDefinition)

        this.previewUrl = task;
        this.previewVisible = true;
        this.currentPage = 1;
        this.$message.success("PDF预览已生成");
      } catch (error) {
        console.error("PDF生成失败:", error);
        this.$message.error("PDF生成失败，请重试");
      } finally {
        this.previewLoading = false;
      }
    },

    /**
     * 处理PDF打印
     * 使用pdfmake生成PDF并调用打印功能
     */
    async handlePrint() {
      this.printLoading = true;
      try {
        const docDefinition = PdfService.createBusinessReport(this.formData);
        PdfService.openPdfPreview(docDefinition);
        this.$message.success("PDF打印已准备就绪");
      } catch (error) {
        console.error("PDF打印失败:", error);
        this.$message.error("PDF打印失败，请重试");
      } finally {
        this.printLoading = false;
      }
    },

    /**
     * 处理PDF下载
     * 使用pdfmake生成PDF并下载
     */
    async handleDownload() {
      this.downloadLoading = true;
      try {
        const docDefinition = PdfService.createBusinessReport(this.formData);
        const fileName = `业务报告-${this.formData.reportNo}.pdf`;
        PdfService.downloadPdf(docDefinition, fileName);
        this.$message.success("PDF下载已开始");
      } catch (error) {
        console.error("PDF下载失败:", error);
        this.$message.error("PDF下载失败，请重试");
      } finally {
        this.downloadLoading = false;
      }
    },

    /**
     * 返回上一页
     * 导航回业务概览页面
     */
    goBack() {
      this.$router.push("/business");
    },
  },

  beforeDestroy() {
    // 清理Blob URL
    if (this.previewUrl) {
      URL.revokeObjectURL(this.previewUrl);
    }
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .header {
    text-align: center;
    margin-bottom: 30px;

    h1 {
      color: #303133;
      margin-bottom: 10px;
    }

    .description {
      color: #606266;
      font-size: 14px;
    }
  }

  .pdf-controls {
    margin-bottom: 20px;

    .form-panel {
      .el-form-item {
        margin-bottom: 15px;
      }
    }

    .action-buttons {
      display: flex;
      justify-content: center;
      gap: 10px;
      margin-top: 20px;

      .el-button {
        min-width: 120px;
      }
    }
  }

  .pdf-preview-container {
    height: 80vh;
    display: flex;
    flex-direction: column;

    .preview-toolbar {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      background: #f5f5f5;
      border-bottom: 1px solid #dcdfe6;

      .page-info {
        margin: 0 20px;
        color: #606266;
      }
    }

    .pdf-viewer {
      flex: 1;
      overflow: auto;
      background: #f8f8f8;
      display: flex;
      justify-content: center;
      align-items: flex-start;
      padding: 20px;

      .pdf-document {
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        background: white;
      }
    }
  }
}

/* 全屏样式 */
:fullscreen .pdf-preview-container {
  height: 100vh;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }

  .action-buttons {
    flex-direction: column;

    .el-button {
      width: 100%;
      margin-bottom: 10px;
    }
  }
}
</style>
